<!DOCTYPE html>
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0" charset = "UTF-8">
<html>
	<head>
		<title>数据生成</title>	
	</head>
	<body>
        <input type = "file" id = "input"/>
        <button id = "convBtn">生成</button>
	</body>
    <script lang = "javascript" src = "dist/xlsx.full.min.js"></script>
    <script>

        document.getElementById("convBtn").addEventListener("click", function() {
            let file = document.querySelector('input').files[0]
            readWorkbookFromLocalFile(file, (workbook) => {
                dataConv(file, workbook)
            })
        });

        function dataConv(file, workbook)
        {
            let name = file.name.split('.')[0]
            let data = dataConvHelper(workbook)
            let outputName = `${name}.js`
            let outputString = `var ${name} = ${data}`
            download(outputName, outputString)
        }

        function download(filename, text) {
            var element = document.createElement('a');
            element.setAttribute('href', 'data:text/plain;charset=utf-16,' + encodeURIComponent(text));
            element.setAttribute('download', filename);
            element.style.display = 'none';
            document.body.appendChild(element);
            element.click();
            document.body.removeChild(element);
        }

        function dataConvHelper(workbook)
        {
            let jObjects = XLSX.utils.sheet_to_json(readFirstSheetFromWorkbook(workbook))
            let bias = 2
            let jObjectsFixed = {}
            for(let i in jObjects)
            {
                jObjectsFixed[parseInt(i) + bias] = jObjects[i]
            }
            return recoverWhiteSpaceSymbols(JSON.stringify(jObjectsFixed))
        }

        function recoverWhiteSpaceSymbols(string)
        {
            string = string.replace(/\\\\/g, "\\");
            return string
        }
        
        function readWorkbookFromLocalFile(file, callback) {
            let reader = new FileReader();
            reader.onload = function(e) {
                let data = e.target.result;
                let workbook = XLSX.read(data, {type: 'binary'});
                if(callback) callback(workbook);
            };
            reader.readAsBinaryString(file);
        }

        function readFirstSheetFromWorkbook(workbook)
        {
            let sheetNames = workbook.SheetNames
            return workbook.Sheets[sheetNames[0]]
        }

    </script>
</html>